from PySide6.QtWidgets import QWidget, QComboBox, QLineEdit
from ...Input import Input
from ..ScriptWidget import ScriptWidget
from enums.VarCompareType import VarCompareType
from enums.ZhVarCompareType import ZhVarCompareType


class VarCompare(QWidget):
    def __init__(self, parent: QWidget):
        super(VarCompare, self).__init__(parent)

        lineHeight = int(parent.height() / 2)

        self.inputVarName = Input(self, '变量')
        self.inputVarName.setMaxLength(6)
        self.inputVarName.setInputType('string')
        self.inputVarName.setFixedHeight(lineHeight)

        self.comVarCompareType = QComboBox(self)
        self.comVarCompareType.addItems(ZhVarCompareType.values())
        self.comVarCompareType.setCurrentIndex(0)
        self.comVarCompareType.setGeometry(
            self.inputVarName.width() + 10, 0,
            self.comVarCompareType.width(), lineHeight
        )

        self.editValue = QLineEdit(self)
        self.editValue.setMaxLength(6)
        self.editValue.setGeometry(
            self.comVarCompareType.x() + self.comVarCompareType.width() + 10, 0,
            self.inputVarName.edit.width(), lineHeight
        )

        self.setFixedSize(self.editValue.x() + self.editValue.width(), lineHeight)

    @property
    def data(self):
        varCompareTypeName = ZhVarCompareType(self.comVarCompareType.currentText()).name
        varCompareType = VarCompareType[varCompareTypeName].value
        value = self.editValue.text()
        if varCompareType != 'contain':
            value = int(value)

        return {
            'var_name': self.inputVarName.text,
            'compare_type': varCompareType,
            'value': value
        }

    @data.setter
    def data(self, data):
        # self.setData(data)
        self.inputVarName.text = data['var_name']
        self.comVarCompareType.setCurrentText(ZhVarCompareType[data['compare_type'].upper()].value)
        self.editValue.setText(str(data['value']))

    @staticmethod
    def verify(conditionInfo, env):
        varName = conditionInfo['var_name']
        compareType = conditionInfo['compare_type']
        value = conditionInfo['value']

        if varName not in env.keys():
            return False

        varValue = env[varName]
        if compareType == VarCompareType.EQ.value:
            return int(varValue) == value
        elif compareType == VarCompareType.NE.value:
            return int(varValue) != value
        elif compareType == VarCompareType.GT.value:
            return int(varValue) > value
        elif compareType == VarCompareType.GE.value:
            return int(varValue) >= value
        elif compareType == VarCompareType.LT.value:
            return int(varValue) < value
        elif compareType == VarCompareType.LE.value:
            return int(varValue) <= value
        elif compareType == VarCompareType.CONTAIN.value:
            return value in varValue

        return False
